<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
    <el-form ref="formRef" :model="formData" label-width="100px" v-loading="formLoading" disabled>
      <el-form-item label="日期" prop="registrationDate">
        <el-date-picker v-model="formData.registrationDate" type="date" value-format="x" placeholder="选择日期" />
      </el-form-item>

      <el-form-item label="车间名" prop="workshopName">
        <el-tree-select v-model="formData.workshopName" :data="deptTree" :props="defaultProps" check-strictly filterable
          clearable default-expand-all placeholder="请选择车间" value-key="id" @change="handleWorkshopChange" />
      </el-form-item>

      <el-form-item label="提出人" prop="proposer">
        <el-select v-model="formData.proposer" filterable clearable placeholder="请选择提出人" style="width: 100%;">
          <el-option v-for="dict in userList" :key="dict.id" :label="dict.nickname" :value="dict.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="停线类型" prop="category">
        <el-select v-model="formData.category" placeholder="请选择停线类型" style="width: 100%;">
          <el-option v-for="dict in category" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="停线问题" prop="question">
        <el-input v-model="formData.question" placeholder="请输入停线问题" />
      </el-form-item>

      <el-form-item label="停线原因" prop="reason">
        <el-input v-model="formData.reason" placeholder="请输入停线原因" />
      </el-form-item>

      <el-col :span="16">
        <el-form-item label="开始时间" prop="startTime" label-width="100px">
          <el-date-picker v-model="formData.startTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD HH:mm" placeholder="开始时间" style="width: 100%;" @change="calculateDuration" />
        </el-form-item>
      </el-col>

      <el-col :span="16">
        <el-form-item label="结束时间" prop="endTime" label-width="100px">
          <el-date-picker v-model="formData.endTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD HH:mm" placeholder="结束时间" style="width: 100%;" @change="calculateDuration" />
        </el-form-item>
      </el-col>

      <el-form-item label="持续时间(分钟)" prop="duration">
        <el-input v-model="formData.duration" placeholder="请输入持续时间(分钟)" />
      </el-form-item>

      <el-form-item label="责任部门" prop="responsibleDepartment">
        <el-tree-select v-model="formData.responsibleDepartment" :data="deptTree" :props="defaultProps" check-strictly
          filterable clearable default-expand-all placeholder="请选择责任部门" value-key="id" />
      </el-form-item>

      <el-form-item label="责任人" prop="respersonids">
        <el-select clearable multiple filterable v-model="formData.respersonids" placeholder="请选择维修人">
          <el-option v-for="dict in userList" :key="dict.id" :label="dict.nickname" :value="dict.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="影响人数" prop="numberOfAffected">
        <el-input v-model="formData.numberOfAffected" placeholder="请输入影响人数" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { LinestopRegistrationApi, LinestopRegistration } from '@/api/mold/linestopregistration'
import { LinestopCategoryApi } from '@/api/mold/linestopcategory'
import { defaultProps, handleTree } from '@/utils/tree'
import * as UserApi from '@/api/system/user'
import * as DeptApi from '@/api/system/dept'
/** 停线登记 查询 */
defineOptions({ name: 'LinestopRegistrationQuery' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref<{
  id: number | undefined,
  registrationDate: number | undefined,
  workshopName: number | undefined,
  proposer: number | undefined,
  category: number | undefined,
  categoryName: string | undefined,
  question: string | undefined,
  reason: string | undefined,
  startTime: string | number | undefined,
  endTime: string | number | undefined,
  duration: string | undefined,
  responsibleDepartment: number | undefined,
  respersonids: number[],
  respersons: string | undefined,
  numberOfAffected: number | string | undefined,
  submitIf: number | undefined
}>({
  id: undefined,
  registrationDate: undefined,
  workshopName: undefined,
  proposer: undefined,
  category: undefined,
  categoryName: undefined,
  question: undefined,
  reason: undefined,
  startTime: undefined,
  endTime: undefined,
  duration: undefined,
  responsibleDepartment: undefined,
  respersonids: [],
  respersons: undefined,
  numberOfAffected: undefined,
  submitIf: undefined
})
const formRef = ref() // 表单 Ref
const deptTree = ref() // 树形结构
const category = ref([]) // 树形结构

//用户列表
import type { UserVO } from '@/api/system/user'
const userList = ref<UserVO[]>([])

/**
 * 计算持续时间(分钟)
 */
const calculateDuration = () => {
  if (formData.value.startTime && formData.value.endTime) {
    const startTime = new Date(formData.value.startTime).getTime()
    const endTime = new Date(formData.value.endTime).getTime()
    if (!isNaN(startTime) && !isNaN(endTime) && endTime >= startTime) {
      const diffMs = endTime - startTime
      const diffMins = Math.floor(diffMs / (1000 * 60))
      formData.value.duration = diffMins.toString()
    }
  }
}

/**
 * 当车间名改变时，获取部门详情并将leaderUserId赋值给proposer
 */
const handleWorkshopChange = async (val: any) => {
  if (val) {
    try {
      const deptDetail = await DeptApi.getDept(val)
      if (deptDetail.leaderUserId) {
        formData.value.proposer = deptDetail.leaderUserId
      }
    } catch (error) {
      console.error('获取部门详情失败:', error)
    }
  }
}

/** 打开弹窗 */
const open = async (id: number) => {
  await initData()
  await getCategory()
  dialogVisible.value = true
  dialogTitle.value = '查看停线登记'
  resetForm()
  // 设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await LinestopRegistrationApi.getLinestopRegistration(id)
      // 转换车间名为数字类型
      if (data.workshopName) {
        data.workshopName = Number(data.workshopName)
      }
      if (data.proposer) {
        data.proposer = Number(data.proposer)
      }

      if (data.responsibleDepartment) {
        data.responsibleDepartment = Number(data.responsibleDepartment)
      }

      // 将时间戳转换为 YYYY-MM-DD HH:mm:ss 格式
      if (data.startTime) {
        const startTimeDate = new Date(data.startTime);
        const year = startTimeDate.getFullYear();
        const month = String(startTimeDate.getMonth() + 1).padStart(2, '0');
        const day = String(startTimeDate.getDate()).padStart(2, '0');
        const hours = String(startTimeDate.getHours()).padStart(2, '0');
        const minutes = String(startTimeDate.getMinutes()).padStart(2, '0');
        const seconds = String(startTimeDate.getSeconds()).padStart(2, '0');
        data.startTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }
      if (data.endTime) {
        const endTimeDate = new Date(data.endTime);
        const year = endTimeDate.getFullYear();
        const month = String(endTimeDate.getMonth() + 1).padStart(2, '0');
        const day = String(endTimeDate.getDate()).padStart(2, '0');
        const hours = String(endTimeDate.getHours()).padStart(2, '0');
        const minutes = String(endTimeDate.getMinutes()).padStart(2, '0');
        const seconds = String(endTimeDate.getSeconds()).padStart(2, '0');
        data.endTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const initData = async () => {
  userList.value = await UserApi.getSimpleUserList()
  await getTree()
}

/** 获得部门树 */
const getTree = async () => {
  deptTree.value = []
  let parentId = 115
  const data = await DeptApi.getDeptsById(parentId)
  let dept: Tree = { id: parentId, name: '阿能集团', children: [] }
  dept.children = handleTree(data)
  deptTree.value.push(dept)
  console.log(deptTree.value)
}

//获取所有分类
const getCategory = async () => {
  const res = await LinestopCategoryApi.getLinestopCategoryAll();
  category.value = res
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    registrationDate: undefined,
    workshopName: undefined,
    proposer: undefined,
    category: undefined,
    categoryName: undefined,
    question: undefined,
    reason: undefined,
    startTime: undefined,
    endTime: undefined,
    duration: undefined,
    responsibleDepartment: undefined,
    respersonids: [],
    respersons: undefined,
    numberOfAffected: undefined,
    submitIf: undefined
  }
  formRef.value?.resetFields()
}
</script>